package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/11/24.<br><br>
 *
 * 中等：螺旋矩阵 II
 */
public class Topic59 {

    public static void main(String[] args) {
        Topic59 instance = new Topic59();

        Util.printArray(instance.generateMatrix(1));
        Util.printArray(instance.generateMatrix(2));
        Util.printArray(instance.generateMatrix(3));
    }

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];

        int value = 1;
        int left = 0;
        int top = 0;
        int right = n - 1;
        int bottom = n - 1;

        while (left <= right && top <= bottom) {

            for(int col = left; col <= right; col++) {
                matrix[top][col] = value++;
            }

            for(int row = top + 1; row <= bottom; row++) {
                matrix[row][right] = value++;
            }

            if(left < right && top < bottom) {
                for(int col = right - 1; col > left; col--) {
                    matrix[bottom][col] = value++;
                }

                for(int row = bottom; row > top; row--) {
                    matrix[row][left] = value++;
                }
            }

            left++;
            top++;
            right--;
            bottom--;
        }

        return matrix;
    }

    public int[][] generateMatrix2(int n) {
        int[][] matrix = new int[n][n];

        int value = 1;
        int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directionIndex = 0;

        int row = 0;
        int col = 0;
        for(int i = 0; i < n * n; i++) {
            matrix[row][col] = value++;

            int nextRow = row + direction[directionIndex][0];
            int nextCol = col + direction[directionIndex][1];
            if(nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol] != 0) {
                directionIndex = (directionIndex + 1) % 4;
            }

            row += direction[directionIndex][0];
            col += direction[directionIndex][1];
        }

        return matrix;
    }
}
